package wb.is.besti.edu.cd.emergency_responsesys.utils;

import com.baidu.mapapi.http.HttpClient;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import wb.is.besti.edu.cd.emergency_responsesys.R;

public class NewsService {

    public static List<News> getJSONLastNews(){
        String path="http://152.136.46.15/NewsJson/EventServlet";
        HttpURLConnection connection = null;
        List<News> newsList = new ArrayList<>();
        try {
            connection = (HttpURLConnection)new URL(path).openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("POST");
            if (connection.getResponseCode()==200){
                InputStream json = connection.getInputStream();
                newsList = parseJSON(json);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (connection !=null){
                connection.disconnect();
            }
        }
        return newsList;
    }
    private static List<News> parseJSON(InputStream jsonStream) throws Exception{
        List<News> list = new ArrayList<News>();
        byte[] data = StreamTool.read(jsonStream);
        String json = new String(data);
        JSONArray jsonArray = new JSONArray(json);
        for (int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String title = jsonObject.getString("title");
            String desc = jsonObject.getString("desc");
            list.add(new News(title,desc,R.mipmap.news_one));
        }
        return list;
    }
}
